<template>
  <view class="page">
    <uni-nav-bar
      :fixed="true"
      :statusBar="true"
      left-icon="left"
      title="新增商品"
      @clickLeft="handleBack"
    />
    <view class="container">
      <!-- 商品分类 -->
      <view class="form-item required">
        <text class="label">商品一级分类</text>
        <uni-data-select
          class="select"
          placeholder="请选择商品一级分类"
          v-model="form.commodityClassifyLevel1"
          :localdata="level1ClassList"
          @change="handleLevel1Change"
        />
      </view>

      <!-- <view class="form-item"> -->
      <!--   <text class="label">商品二级分类</text> -->
      <!--   <uni-data-select -->
      <!--     class="select" -->
      <!--     placeholder="请选择商品二级分类" -->
      <!--     v-model="form.commodityClassifyLevel2" -->
      <!--     :localdata="level2ClassList" -->
      <!--     :disabled="!form.commodityClassifyLevel1" -->
      <!--   /> -->
      <!-- </view> -->

      <!-- 商品基本信息 -->
      <view class="form-item required">
        <text class="label">商品名称</text>
        <input class="input" v-model="form.name" placeholder="请输入商品名称" />
      </view>

      <view class="form-item">
        <text class="label">规格</text>
        <input class="input" v-model="form.standard" placeholder="请输入规格" />
      </view>

      <view class="form-item">
        <text class="label">尺码</text>
        <input class="input" v-model="form.sizes" placeholder="请输入尺码" />
      </view>

      <view class="form-item">
        <text class="label">型号</text>
        <input class="input" v-model="form.model" placeholder="请输入型号" />
      </view>

      <!-- 价格信息 -->
      <view class="form-item required">
        <text class="label">市场价</text>
        <input
          class="input"
          v-model.number="form.marketMoney"
          type="digit"
          placeholder="请输入市场价"
        />
      </view>

      <view class="form-item required">
        <text class="label">单价</text>
        <input
          class="input"
          v-model.number="form.money"
          type="digit"
          placeholder="请输入单价"
        />
      </view>

      <!-- 库存 -->
      <view class="form-item required">
        <text class="label">库存</text>
        <input
          class="input"
          v-model.number="form.stock"
          type="number"
          placeholder="请输入库存"
        />
      </view>

      <!-- 让利比率 -->
      <view class="form-item required">
        <text class="label">让利比率</text>
        <uni-data-select
          class="select"
          placeholder="请选择让利比率"
          v-model="form.offerDiscountsRatio"
          :localdata="discountRatioList"
        />
      </view>

      <!-- 商品图片 -->
      <view class="form-item required">
        <text class="label">展示图片</text>
        <UploadMedia
          v-model="showPicList"
          :max-count="1"
          :max-size="5"
          upload-text="上传展示图"
          upload-type="image"
          @change="handleShowPicChange"
        />
      </view>

      <!-- 轮播图 -->
      <view class="form-item">
        <text class="label">轮播图</text>
        <UploadMedia
          v-model="carouselList"
          :max-count="3"
          :max-size="5"
          upload-text="上传轮播图"
          upload-type="image"
          tip-text="最多上传3张图片"
          :enable-drag="true"
          @change="handleCarouselChange"
        />
      </view>

      <!-- 商品详情 -->
      <view class="form-item">
        <text class="label">商品详情</text>
        <view class="edit-btn" @click="editDetails">编辑详情</view>
      </view>
      <view class="detail-preview" v-if="form.contextDetails">
        <view class="preview-title">详情预览</view>
        <mp-html :content="form.contextDetails" />
      </view>

      <!-- 说明 -->
      <view class="form-item">
        <text class="label">说明</text>
        <textarea
          class="textarea"
          v-model="form.explains"
          placeholder="请输入商品说明"
          :maxlength="500"
        />
      </view>

      <!-- 其他信息 -->
      <view class="form-item">
        <text class="label">产品编码</text>
        <input
          class="input"
          v-model="form.product"
          placeholder="请输入产品编码"
        />
      </view>

      <view class="form-item">
        <text class="label">供应商</text>
        <input
          class="input"
          v-model="form.supplier"
          placeholder="请输入供应商"
        />
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn" @click="handleSubmit">提交</view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useEditorStore } from "@/store/modules/editor";
import { useUserStore } from "@/store/modules/user";
import { useStoreStore } from "@/store/modules/store";
import { addGoods, getGoodsClassify } from "@/api/goods";
import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html";
import UploadMedia from "@/components/UploadMedia/UploadMedia.vue";

const editorStore = useEditorStore();
const userStore = useUserStore();
const storeStore = useStoreStore();

// 表单数据
const form = ref({
  userId: null,
  commodityClassifyLevel1: null,
  commodityClassifyLevel2: null,
  name: null,
  standard: null,
  sizes: null,
  model: null,
  marketMoney: null,
  money: null,
  showPic: null,
  contextDetails: null,
  explains: null,
  showDetails1: null,
  showDetails2: null,
  showDetails3: null,
  link1: null,
  link2: null,
  link3: null,
  stock: null,
  merchantId: null,
  product: null,
  supplier: null,
  offerDiscountsRatio: null,
});

// 图片列表（用于 UploadMedia 组件）
const showPicList = ref([]);
const carouselList = ref([]);

// 商品分类列表
const level1ClassList = ref([]);
const level2ClassList = ref([]);

// 让利比率列表（3%-20%）
const discountRatioList = ref([]);

// 初始化让利比率列表
const initDiscountRatioList = () => {
  const list = [];
  for (let i = 3; i <= 20; i++) {
    list.push({
      value: i,
      text: `${i}%`,
    });
  }
  discountRatioList.value = list;
};

// 获取一级分类列表
const getLevel1ClassList = async () => {
  try {
    const res = await getGoodsClassify({
      pluralId: 0,
      classifyPid: 0,
    });

    if (res.data) {
      level1ClassList.value = res.data.map((item) => ({
        value: item.id,
        text: item.classifyName,
      }));
    }
  } catch (error) {
    console.error("获取一级分类失败:", error);
    uni.showToast({
      title: "获取分类失败",
      icon: "none",
    });
  }
};

// 获取二级分类列表
const getLevel2ClassList = async (parentId) => {
  try {
    const res = await getGoodsClassify({
      pluralId: 0,
      classifyPid: parentId,
    });

    if (res.data) {
      level2ClassList.value = res.data.map((item) => ({
        value: item.id,
        text: item.classifyName,
      }));
    } else {
      level2ClassList.value = [];
    }
  } catch (error) {
    console.error("获取二级分类失败:", error);
    level2ClassList.value = [];
  }
};

// 一级分类变更
const handleLevel1Change = (value) => {
  // 清空二级分类
  form.value.commodityClassifyLevel2 = null;
  level2ClassList.value = [];

  // 加载二级分类
  if (value) {
    getLevel2ClassList(value);
  }
};

// 展示图片变化
const handleShowPicChange = (fileList) => {
  if (fileList && fileList.length > 0) {
    form.value.showPic = fileList[0].url;
  } else {
    form.value.showPic = null;
  }
};

// 轮播图变化
const handleCarouselChange = (fileList) => {
  form.value.showDetails1 = fileList[0]?.url || null;
  form.value.showDetails2 = fileList[1]?.url || null;
  form.value.showDetails3 = fileList[2]?.url || null;
};

// 编辑商品详情
const editDetails = () => {
  editorStore.setRichText(form.value.contextDetails || "");
  uni.navigateTo({ url: "./editDetails" });
};

// 提交表单
const handleSubmit = async () => {
  // 验证必填项
  if (!form.value.commodityClassifyLevel1) {
    uni.showToast({ title: "请输入商品一级分类", icon: "none" });
    return;
  }
  if (!form.value.name) {
    uni.showToast({ title: "请输入商品名称", icon: "none" });
    return;
  }
  if (!form.value.marketMoney) {
    uni.showToast({ title: "请输入市场价", icon: "none" });
    return;
  }
  if (!form.value.money) {
    uni.showToast({ title: "请输入单价", icon: "none" });
    return;
  }
  if (!form.value.stock) {
    uni.showToast({ title: "请输入库存", icon: "none" });
    return;
  }
  if (!form.value.showPic) {
    uni.showToast({ title: "请上传展示图片", icon: "none" });
    return;
  }
  if (!form.value.offerDiscountsRatio) {
    uni.showToast({ title: "请选择让利比率", icon: "none" });
    return;
  }

  // 从编辑器获取最新内容
  if (editorStore.richText) {
    form.value.contextDetails = editorStore.richText;
  }

  // 确保 merchantId 和 userId
  form.value.merchantId = Number(storeStore.storeId) || 0;
  form.value.userId = userStore.userInfo?.userId;

  // 转换让利比率：从百分比整数转为小数（例如 3 转为 0.03）
  const submitData = {
    ...form.value,
    offerDiscountsRatio: form.value.offerDiscountsRatio / 100,
  };

  try {
    uni.showLoading({ title: "提交中..." });
    const res = await addGoods(submitData);
    uni.hideLoading();

    uni.showToast({
      title: res.message || "添加成功",
      icon: "none",
    });

    if (res.code === 2000) {
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    }
  } catch (error) {
    uni.hideLoading();
    console.error("添加商品失败:", error);
    uni.showToast({
      title: "添加失败",
      icon: "none",
    });
  }
};

// 返回
const handleBack = () => {
  uni.navigateBack();
};

// 页面加载
onLoad(() => {
  userStore.hydrateFromStorage();
  storeStore.hydrateFromStorage();
  form.value.userId = userStore.userInfo?.userId;
  form.value.merchantId = Number(storeStore.storeId) || 0;

  // 加载一级分类列表
  getLevel1ClassList();
  // 初始化让利比率列表
  initDiscountRatioList();
});

// 页面显示
onShow(() => {
  userStore.hydrateFromStorage();
  storeStore.hydrateFromStorage();

  // 更新富文本内容
  if (editorStore.richText) {
    form.value.contextDetails = editorStore.richText;
  }

  // 确保 merchantId 始终最新
  form.value.merchantId = Number(storeStore.storeId) || 0;
});
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f6f7f9;
  padding-bottom: 120rpx;
}

.container {
  padding: 24rpx;
}

.form-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;

  &.required .label::before {
    content: "*";
    color: #ff4d4f;
    margin-right: 8rpx;
  }

  .label {
    display: block;
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 16rpx;
  }

  .input {
    width: 100%;
    height: 80rpx;
    padding: 0 20rpx;
    background: #f6f7f9;
    border: 2rpx solid #e8eaed;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #333;
    line-height: 80rpx;

    &:focus {
      border-color: #667eea;
      background: #fff;
    }
  }

  .select {
    width: 100%;
    height: 80rpx;
    //background: #f6f7f9;
    //border: 2rpx solid #e8eaed;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #333;
  }

  .textarea {
    width: 100%;
    min-height: 200rpx;
    padding: 20rpx;
    background: #f6f7f9;
    border: 2rpx solid #e8eaed;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
  }

  .mt-12 {
    margin-top: 12rpx;
  }

  .edit-btn {
    display: inline-block;
    padding: 12rpx 24rpx;
    background: #e8f0ff;
    color: #667eea;
    border-radius: 8rpx;
    font-size: 26rpx;
    font-weight: 600;
  }
}

.detail-preview {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;

  .preview-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 16rpx;
  }
}

.submit-btn {
  position: fixed;
  bottom: 24rpx;
  left: 24rpx;
  right: 24rpx;
  height: 88rpx;
  background: #ffbc00;
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
